import React, { useEffect } from 'react';
import { Select } from 'antd';
import { changeProject, getProject, getProjects } from '@/store/slice/config';

export default function GlobalProject() {
  const dispatch = useAppDispatch();
  const projects = useAppSelector(getProjects);
  const currentProject = useAppSelector(getProject);
  const [options, setOptions] = useState<{ label: string; value: string }[]>();
  const [selectValue, setSelectValue] = useState<string>();

  const handleChange = (value: string) => {
    setSelectValue(value);
    const project = projects?.find(ele => ele.id.toString() === value);
    if (project) {
      dispatch(changeProject(project));
    }
  };

  useEffect(() => {
    const _options = [] as { label: string; value: string }[];
    projects.forEach(ele => {
      _options.push({
        label: ele.projectName,
        value: ele.id.toString()
      });
    });
    setOptions(_options);
    if (currentProject) {
      setSelectValue(currentProject.id.toString());
    }
  }, []);

  return (
    <Select
      style={{ width: '200px' }}
      onChange={handleChange}
      value={selectValue}
      options={options}
    />
  );
}
